package org.madgecko.api.controller;

import org.madgecko.api.model.Member;
import org.madgecko.api.model.Record;
import org.madgecko.api.service.iface.IMemberService;
import org.madgecko.api.service.iface.IRecordService;
import org.madgecko.basic.model.AjaxReturn;
import org.madgecko.basic.model.Pager;
import org.madgecko.basic.model.User;
import org.madgecko.basic.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.List;

/**
 * Author       : MadFrog
 * Date         : 2019/6/16 13:06
 * Description  : 蜂人工作室打卡App接口
 */
@Controller
@RequestMapping("/daka")
public class DakaController {

    @Autowired
    private IMemberService memberService;
    @Autowired
    private IRecordService recordService;


    /**
     * 绑定GPS坐标
     * @param longtitude
     * @param latitude
     * @param imei
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/bindlocation", method = RequestMethod.GET)
    public AjaxReturn bindlocation(@NotNull Double longtitude, @NotNull Double latitude, @NotNull String imei, HttpSession session){
        Member member = (Member) session.getAttribute("user");
        if( longtitude>0 && latitude>0 && !"".equals(imei)){
            member.setLongtitude(longtitude);
            member.setLatitude(latitude);
            member.setPhoneIMEI(imei);
            memberService.update(member);
            return new AjaxReturn(true, "绑定GPS坐标成功");
        }else{
            return new AjaxReturn(false, "参数不完整");
        }
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public AjaxReturn login(@NotNull String username, @NotNull String password, @NotNull Double longtitude, @NotNull Double latitude, HttpSession session){
        try {
            User m = memberService.loadByUserName(username);
            if(m==null){
                return new AjaxReturn(false, null, "用户名或密码错误");
            }
            // 验证密码
            String pagePwd = SecurityUtil.md5(password);
            if(!m.getPassword().equals(pagePwd)){
                return new AjaxReturn(false, null, "用户名或密码错误");
            }
            // 为当前会话session存入属性user
            session.setAttribute("user", m);
            System.out.println(session.getId());
            return new AjaxReturn(true, m, "member");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return new AjaxReturn(false, "md5加密异常");
        }
    }

    /**
     *
     * @param recordId      全新打卡传0，非全新打卡传前任recordId（非零）
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/daka", method = RequestMethod.GET)
    public AjaxReturn daka(@NotNull Boolean isValid, @NotNull Integer recordId, HttpSession session){
        if(isValid!=null && isValid){
            Member member = (Member) session.getAttribute("user");
            Integer memberId = member.getId();
            member = memberService.load(memberId);
            member.setScore(member.getScore()+1);
            memberService.update(member);
            Record record = null;
            if(recordId!=0){
                // 持续打卡
                record = recordService.load(recordId);
                record.setEndTime(new Timestamp(System.currentTimeMillis()));
                record.setScore(record.getScore()+1);
                recordService.update(record);
            }else {
                // 全新打卡
                record = new Record();
                record.setMember(member);
                Long start = System.currentTimeMillis() - 40*1000L;       // 当前时间减6分钟才是开始打卡的开始计时时间，因为定时器是先计时后执行
                record.setStartTime(new Timestamp(start));
                record.setEndTime(new Timestamp(System.currentTimeMillis()));
                record.setFrequency(recordService.countRecordByMember(memberId)+1);
                record.setScore(1);
                recordService.add(record);
            }
            return new AjaxReturn(true, record, "打卡成功");
        }else {
            return new AjaxReturn(false,"打卡无效");
        }
    }

    /**
     * 排行榜
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/ranking", method = RequestMethod.GET)
    public AjaxReturn statistic(){
        List<Member> members = memberService.listAllByScore();
        return new AjaxReturn(true, members);
    }

    /**
     * 我的得分纪录
     * @return 打卡记录主键
     * 分页
     */
    @ResponseBody
    @RequestMapping(value = "/history", method = RequestMethod.GET)
    public AjaxReturn history(HttpSession session){
        Member member = (Member)session.getAttribute("user");
        Pager<Record> recordPager = recordService.findByMember(member.getId());
        return new AjaxReturn(true, recordPager.getDatas(), recordPager.getTotal());
    }

}
